﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
using HF.WorkFlow.Engine;
using HF.WorkFlow.Template;
using eWorld.UI;
using HF.Framework;
using HF.Framework.Log;
using HF.BaseWebCtrlLib;
using HF.WorkFlow.Const;
using HF.WorkFlow.DataContract;
using HF.Framework.Web;
using HF.Forms.Data;
using System.Collections.Generic;
//using ServiceReferences;

public partial class StartWorkflow : System.Web.UI.Page
{
    string UserId = "";
    string WorkflowId = "";
    string WorktaskId = "";
    string WorkflowInsId = "";
    string WorktaskInsId = "";
    string pageState = "";//新建,修改,查看
    ArrayList UserCtrlList=new ArrayList();//控件列表
    //ServiceReferences.WorkFlowServiceClient workflow = new ServiceReferences.WorkFlowServiceClient();

    protected void Page_Load(object sender, EventArgs e)
    {
        UserId = this.Page.User.Identity.Name;
        try
        {
            if (!IsPostBack)
            {
                BaseUserPage.LoadWaitPage();
                lbWorkflowInsId.Text = Guid.NewGuid().ToString();
                lbWorktaskInsId.Text = Guid.NewGuid().ToString();

                tbxFlowNo.Text = WorkFlowInstance.GetWorkFlowNO();
            }
            
            InitData();
        }
        catch(Exception ex )
        {
            LogData.WriteLog("平台打开启动界面错误:" + ex, lbWorkflowInsId.Text);
            
        }
        finally
        {
            if (!IsPostBack)
                BaseUserPage.FreeWaitPage();
        }

    }
    private void InitData()
    {
        if (Request["WorkflowId"] != null && Request["WorktaskId"] != null)
        {
            WorkflowId = Request["WorkflowId"].ToString();
            WorktaskId = Request["WorktaskId"].ToString();
            //WorkflowId ="7b23d86d-006a-40b8-9f90-51105d1d4ed3";
            //WorktaskId ="7fb02e7f-7a6c-4a4e-833f-573cb5f8ebe9";
            if (tbxWorkflowCaption.Text.Length < 1)
            {
                WorkFlowEntity entity = WorkFlowTemplate.GetInstance().GetWorkFlowEntity(WorkflowId);
                //WorkFlowEntity entity1 = workflow.GetWorkFlowEntity(WorkflowId);     //zhuyun  获取流程实体
                if (entity!=null)
                 tbxWorkflowCaption.Text =entity.FlowCaption + tbxFlowNo.Text;    //zhuyun 业务名称
            }
            WorkflowInsId = lbWorkflowInsId.Text;
            WorktaskInsId = lbWorktaskInsId.Text;
            //加载用户控件
            DataTable dt=MainChildForm.GetInstance().GetWorkTaskFormsView(WorktaskId);
            //DataTable dt = workflow.GetWorkTaskFormsView(WorktaskId);   //zhuyun 20120209 获取任务节点与表单视图
            string ctrlPath = "";
            string ctrlState = "";
            string ctrlID = "";
            pageState = WorkFlowConst.STATE_ADD;
            foreach (DataRow dr in dt.Rows)
            {
                CollapsablePanel panel = new CollapsablePanel();
                panel.CollapseImageUrl = "../Images/collapse.gif";
                panel.ExpandImageUrl = "../Images/expand.gif";
                panel.ExpandText = "展开";
                panel.CollapseText = "关闭";
                panel.Visible = true;
                panel.ExpandText = dr["ChildCaption"].ToString();
                ctrlPath = dr["FilePath"].ToString();
                string filename = Server.MapPath(@"..\" + ctrlPath);//用户控件文件名
                ctrlState = dr["FormState"].ToString();
                ctrlID = dr["FileName"].ToString();
                if (File.Exists(filename))
                {
                    BaseUserControl c = (BaseUserControl)this.LoadControl(@"..\" + ctrlPath);
                    c.ID = ctrlID;//指定id便于取界面元素
                    c.WorkflowId = WorkflowId;
                    c.PageState = pageState;
                    c.CtrlState = ctrlState;
                    c.WorkflowInsId = WorkflowInsId;
                    c.WorktaskId = WorktaskId;
                    c.WorktaskInsId = WorktaskInsId;
                    c.InitUserControl();//执行控件的初始化事件
                    UserCtrlList.Add(c);//加到用户控件列表中
                    panel.Controls.Add(c);
                }
                else
                {
                    Label l = new Label();
                    l.ForeColor = Color.Red;
                    l.Text = filename + "表单文件不存在或者没有配置表单,无法加载表单!";
                    panel.Controls.Add(l);
                   
                }
                ctrlPlace.Controls.Add(panel);
            }
            //加载命令按钮
            generalCmdButton();
            initButton();
        }
    }
    /// <summary>
    /// 常用按钮
    /// </summary>
    private void generalCmdButton()
    {
        Button btnCommand = new Button();
        btnCommand.Text = "草稿";
        btnCommand.Click += new EventHandler(saveButtonEvent);
        cmdBtnPlace.Controls.Add(btnCommand);
        Literal lab1 = new Literal();
        lab1.Text = "&nbsp;&nbsp;";
        cmdBtnPlace.Controls.Add(lab1);

         btnCommand = new Button();
        btnCommand.Text = "打印本表单";
        btnCommand.Click += new EventHandler(PrintClicked);
        generalPlace.Controls.Add(btnCommand);
         lab1 = new Literal();
        lab1.Text = "&nbsp;&nbsp;";
        generalPlace.Controls.Add(lab1);

         btnCommand = new Button();
        btnCommand.Text = "直接打印本表单";
        btnCommand.Click += new EventHandler(PrintPageClicked);
        generalPlace.Controls.Add(btnCommand);
         lab1 = new Literal();
        lab1.Text = "&nbsp;&nbsp;";
        generalPlace.Controls.Add(lab1);

         btnCommand = new Button();
        btnCommand.Text = "打印设置";
        btnCommand.Click += new EventHandler(PageSetupClicked);
        generalPlace.Controls.Add(btnCommand);
         lab1 = new Literal();
        lab1.Text = "&nbsp;&nbsp;";
        generalPlace.Controls.Add(lab1);

         btnCommand = new Button();
        btnCommand.Text = "打印预览";
        btnCommand.Click += new EventHandler(PreviewClicked);
        generalPlace.Controls.Add(btnCommand);
         lab1 = new Literal();
        lab1.Text = "&nbsp;&nbsp;";
        generalPlace.Controls.Add(lab1);
    }
    /// <summary>
    /// 初始化流程命令按钮
    /// </summary>
    private void initButton()
    {
        DataTable taskCommand = WorkTaskCommand.GetInstance().GetTaskCommands(WorktaskId);
        //DataTable taskCommand = workflow.GetTaskCommands(WorktaskId);   //20120209 zhuyun 
        foreach (DataRow dr in taskCommand.Rows)
        {
            string cmdName = dr["CommandName"].ToString();
            Button btnCommand = new Button();
            btnCommand.Text = cmdName;
            btnCommand.Click += new EventHandler(runButtonEvent);
            cmdBtnPlace.Controls.Add(btnCommand);
            Literal lab1 = new Literal();
            lab1.Text = "&nbsp;&nbsp;";
            cmdBtnPlace.Controls.Add(lab1);
        }
    }
    /// <summary>
    /// 保存表单业务数据
    /// </summary>
    private bool  SaveUserControl(bool IsDraft)
    {
        if (pageState == WorkFlowConst.STATE_VIEW) return true;
        if (tbxWorkflowCaption.Text.Length == 0)
        {
            WorkDialog.ShowMessage(this,"流程业务名不能为空!");
            tbxWorkflowCaption.Focus();
            return false;
        }
        try
        {
            foreach (BaseUserControl bc in UserCtrlList)
            {
                if (bc.CtrlState == WorkFlowConst.STATE_VIEW) continue;//查看状态不执行保存
                bc.SaveUserControl(IsDraft);
            }
            return true;
        }
        catch
        {
            throw;
        }
    }
    /// <summary>
    /// 控制流程流转的命令按钮，如提交等
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void runButtonEvent(object sender, EventArgs e)
    {
        if (SaveUserControl(false))
        {
            string command = (sender as Button).Text;
            WorkFlowRuntime wfruntime = new WorkFlowRuntime();
            wfruntime.UserId = UserId;
            wfruntime.WorkFlowId = WorkflowId;
            wfruntime.WorkTaskId = WorktaskId;
            wfruntime.WorkFlowInstanceId = WorkflowInsId;
            wfruntime.WorkTaskInstanceId = WorktaskInsId;
            wfruntime.WorkFlowNo = tbxFlowNo.Text;
            wfruntime.CommandName = command;
            wfruntime.Priority = drpPriority.SelectedValue;
            wfruntime.WorkflowInsCaption = tbxWorkflowCaption.Text;
            wfruntime.IsDraft = false;//保存并执行流程流转
            wfruntime.Start();
            Response.Redirect("tooltip.aspx?worktaskInstanceId=" + WorktaskInsId);
        }
    }
    /// <summary>
    /// 草稿
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void saveButtonEvent(object sender, EventArgs e)
    {
        if (SaveUserControl(true))
        {
            string command = (sender as Button).Text;
            WorkFlowRuntime wfruntime = new WorkFlowRuntime();
            wfruntime.UserId = UserId;
            wfruntime.WorkFlowId = WorkflowId;
            wfruntime.WorkTaskId = WorktaskId;
            wfruntime.WorkFlowInstanceId = WorkflowInsId;
            wfruntime.WorkTaskInstanceId = WorktaskInsId;
            wfruntime.Priority = drpPriority.SelectedValue;
            wfruntime.WorkFlowNo = tbxFlowNo.Text;
            wfruntime.CommandName = command;
            wfruntime.WorkflowInsCaption = tbxWorkflowCaption.Text;
            wfruntime.IsDraft = true;//开始节点需要继续交互，草稿状态，暂不提交
            wfruntime.Start();
            WorkDialog.ShowMessage(this,"保存草稿成功。");
        }
    }
    /// <summary>
    /// 打印本表单
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void PrintClicked(object sender, EventArgs e)
    {
        
        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        builder.Append("<OBJECT id=\"WebBrowser\" classid=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\" height=\"0\" width=\"0\"  style=\"display:none\" VIEWASTEXT></OBJECT>");
        builder.Append("<script language=\"javascript\">");
        builder.Append("document.all.WebBrowser.ExecWB(6,1);history.go(-1);");
        builder.Append("</script>");
        this.RegisterStartupScript("test", builder.ToString());
    }

    /// <summary>
    /// 直接打印本表单
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void PrintPageClicked(object sender, EventArgs e)
    {

        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        builder.Append("<OBJECT id=\"WebBrowser\" classid=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\" height=\"0\" width=\"0\"  style=\"display:none\" VIEWASTEXT></OBJECT>");
        builder.Append("<script language=\"javascript\">");
        builder.Append("document.all.WebBrowser.ExecWB(6,6);history.go(-1);");
        builder.Append("</script>");
        this.RegisterStartupScript("test", builder.ToString());
    }

    /// <summary>
    /// 打印设置
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void PageSetupClicked(object sender, EventArgs e)
    {
        
        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        builder.Append("<OBJECT id=\"WebBrowser\" classid=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\" height=\"0\" width=\"0\"  style=\"display:none\" VIEWASTEXT></OBJECT>");
        builder.Append("<script language=\"javascript\">");
        builder.Append("document.all.WebBrowser.ExecWB(8,1);history.go(-1);");
        builder.Append("</script>");
        this.RegisterStartupScript("test", builder.ToString());
    }

    /// <summary>
    /// 打印预览
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void PreviewClicked(object sender, EventArgs e)
    {

        System.Text.StringBuilder builder = new System.Text.StringBuilder();
        builder.Append("<OBJECT id=\"WebBrowser\" classid=\"CLSID:8856F961-340A-11D0-A96B-00C04FD705A2\" height=\"0\" width=\"0\"  style=\"display:none\" VIEWASTEXT></OBJECT>");
        builder.Append("<script language=\"javascript\">");
        builder.Append("document.all.WebBrowser.ExecWB(7,1);history.go(-1);");
        builder.Append("</script>");
        this.RegisterStartupScript("test", builder.ToString());
    }
   
}
